import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { ProductGroupTreeC, InputNumberC, RangeDateC, SingleDateC, SelectC } from '../../../../../../comps';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import config from './config';
import dictionaryConfig from '../../../../../../utils/dictionaryConfig';
const booleanList = dictionaryConfig.booleanList;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 10, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 13, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
@Form.create()
class InitFormC extends PureComponent {
  state = {
    rangedate: [moment().subtract(1, 'years'), moment().subtract(1, 'days')],
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  componentWillUnmount() {}

  typeRender = (item, index) => {
    const {
      type,
      currentModel,
      globalM: {
        dataDictionary: {
          PORT_OPTIMIZATION_FREQ = [],
          PORT_OPTIMIZATION_OBJECT = [],
          PORT_OPTIMIZATION_COMP_OBJ = [],
          PORT_OPTIMIZATION_BMK = [],
          PORT_OPTIMIZATION_RISK_FREE_RATE = [],
          PORT_OPTIMIZATION_BOND_OBJECT = [],
          PORT_OPTIMIZATION_BOND_COMP_OBJ = [],
        },
      },
    } = this.props;
    const optimize = type == 0 ? PORT_OPTIMIZATION_OBJECT : PORT_OPTIMIZATION_BOND_OBJECT;
    const contrast = type == 0 ? PORT_OPTIMIZATION_COMP_OBJ : PORT_OPTIMIZATION_BOND_COMP_OBJ;
    switch (item.key) {
      case 'portfolio':
        return (
          <Col span={6} key={index}>
            <ProductGroupTreeC form={this.props.form} dataIndex='portfolio' multiple={false} formItemLayout={FormItemLayout} />
          </Col>
        );
      case 'rangeDate':
        return (
          <Col span={6} key={index} className={'dateForm'}>
            <RangeDateC
              initialValue={this.state.rangedate}
              form={this.props.form} // form对象
              title='日期' // 显示名称
              dataIndex={['beginDate', 'endDate']} // Form识别的下拉选项Item ID
              formItemLayout={FormItemLayout}
              required={true}
              message='请选择日期!'
              hasDataED={moment().subtract(1, 'days')}
              onRef={(ref) => {
                this.setState({ RangeDateC: ref });
              }}
            />
          </Col>
        );
      case 'singleDate':
        return (
          <Col span={6} key={index} className={'dateForm'}>
            <SingleDateC
              form={this.props.form} // form对象
              title='日期' // 显示名称
              dataIndex='beginDate' // Form识别的下拉选项Item ID
              formItemLayout={FormItemLayout}
              required={true}
              message='请选择日期!'
              initialValue={moment()}
            />
          </Col>
        );
      case 'rollBacktest':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='滚动回测' // 显示名称
              dataIndex='rollBacktest' // Form识别的Item ID
              dataSource={booleanList}
              initialValue={'0'}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择滚动回测！' }]}
            />
          </Col>
        );
      case 'freq':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='频率' // 显示名称
              dataIndex='freq' // Form识别的Item ID
              dataSource={PORT_OPTIMIZATION_FREQ.map((item) => {
                return { value: item.code, title: item.value };
              })}
              initialValue={'0'}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'滚动优化的时间跨度'}
              rules={[{ required: true, message: '请选择频率！' }]}
              disabled={this.props.form.getFieldsValue().rollBacktest !== '0'}
            />
          </Col>
        );
      case 'optimizeObject':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='优化模型' // 显示名称
              dataIndex='optimizeObject' // Form识别的Item ID
              dataSource={optimize.map((item) => {
                return { value: item.code, title: item.value };
              })}
              initialValue='0'
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择优化模型！' }]}
              onChange={this.selectChange}
            />
          </Col>
        );

      case 'expectReturn':
        return currentModel == 0 ? (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='预期收益率' // 显示名称
              dataIndex='expectReturn' // Form识别的Item ID
              dataSource={booleanList}
              initialValue={'1'}
              onChange={(e) => this.props.handleSelectChange(e, 'expectReturn')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'使用对资产的预期收益率作为优化参数'}
              rules={[{ required: true, message: '请选择预期收益率！' }]}
            />{' '}
          </Col>
        ) : null;

      case 'expectVolatility':
        return currentModel == 0 ? (
          <Col span={6} key={index} style={{ marginRight: '10px' }}>
            <SelectC
              form={this.props.form} // form对象
              title='预期波动率' // 显示名称
              dataIndex='expectVolatility' // Form识别的Item ID
              dataSource={[{ value: '1', title: '否' }]}
              initialValue={'1'}
              onChange={(e) => this.props.handleSelectChange(e, 'expectVolatility')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'使用对资产的预期波动率作为优化参数，需要上传资产的协方差矩阵'}
              rules={[{ required: true, message: '请选择预期波动率！' }]}
            />{' '}
          </Col>
        ) : null;
      case 'riskAversion':
        return currentModel != 0 ? (
          <Col span={6} key={index} style={{ marginRight: '400px' }}>
            <InputNumberC
              form={this.props.form} // form对象
              title='风险厌恶系数' // 显示名称
              dataIndex='riskAversion' // Form识别的Item ID
              initialValue={0.1}
              min={0}
              step={0.1}
              precision={2}
              formItemLayout={FormItemLayout}
              style={{ width: '100%' }}
            />{' '}
          </Col>
        ) : null;
      case 'contrastConfig':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='对比配置' // 显示名称
              dataIndex='contrastConfig' // Form识别的Item ID
              dataSource={contrast.map((item) => {
                return { value: item.code, title: item.value };
              })}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'用以作为对照组，与优化模型的效果进行对比'}
            />
          </Col>
        );
      case 'benchmark':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='业绩比较基准' // 显示名称
              dataIndex='benchmark' // Form识别的Item ID
              dataSource={PORT_OPTIMIZATION_BMK.map((item) => {
                return { value: item.code, title: item.value };
              })}
              optionTitle={true}
              formItemLayout={FormItemLayout}
            />
          </Col>
        );
      case 'assetConst':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='资产约束' // 显示名称
              dataIndex='assetConst' // Form识别的Item ID
              dataSource={booleanList}
              initialValue='1'
              onChange={(e) => this.props.handleSelectChange(e, 'assetConst')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择资产约束！' }]}
            />
          </Col>
        );
      case 'groupConst':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='分组约束' // 显示名称
              dataIndex='groupConst' // Form识别的Item ID
              dataSource={booleanList}
              initialValue='1'
              onChange={(e) => this.props.handleSelectChange(e, 'group')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择分组约束！' }]}
            />
          </Col>
        );
      case 'riskfreeRate':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='无风险利率' // 显示名称
              dataIndex='riskfreeRate' // Form识别的Item ID
              dataSource={PORT_OPTIMIZATION_RISK_FREE_RATE.map((item) => {
                return { value: item.code, title: item.value };
              })}
              optionTitle={true}
              formItemLayout={FormItemLayout}
            />
          </Col>
        );
      case 'robust':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='Robust优化' // 显示名称
              dataIndex='robust' // Form识别的Item ID
              dataSource={[{ value: '1', title: '否' }]}
              initialValue='1'
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'在优化器无法求解的情况下使用MonteCarlo模拟方法求解'}
              rules={[{ required: true, message: '请选择Robust优化！' }]}
            />
          </Col>
        );
    }
  };

  setDataSource = () => {
    let list = [];
    if (this.props.type == '0') {
      list = config.configShock;
    } else if (this.props.type == '1') {
      list = config.bondShock;
    }
    return (
      <div className={'cardBody'}>
        <Form>
          <Row>
            {list.map((item, index) => {
              return this.typeRender(item, index);
            })}
          </Row>
        </Form>
      </div>
    );
  };

  //模板导入
  importData = (data) => {
    if (this.props.type == '0') {
      this.props.form.setFieldsValue({
        assetConst: `${data.assetConst}`,
        beginDate: moment(data.beginDate),
        benchmark: `${data.benchmark}`,
        contrastConfig: `${data.contrastConfig}`,
        endDate: moment(data.endDate),
        expectReturn: `${data.expectReturn}`,
        expectVolatility: `${data.expectVolatility}`,
        freq: `${data.freq}`,
        groupConst: `${data.groupConst}`,
        optimizeObject: `${data.optimizeObject}`,
        portfolio: undefined,
        robust: `${data.robust}`,
        riskAversion: data.riskAversion,
        rollBacktest: `${data.rollBacktest}`,
        riskfreeRate: `${data.riskfreeRate}`,
      });
      this.setState({
        rangedate: [moment(data.beginDate), moment(data.endDate)],
      });
    } else if (this.props.type == '1') {
      console.log(data);
    }
  };

  //优化模型切换
  selectChange = (e) => {
    console.log(this.props.type);
    this.props.selectCurrent(e);
    if (e == 1) {
      //判断优化模型如果选择了多因子模型 预期收益率 预期波动率重置为否
      this.props.form.setFieldsValue({
        expectReturn: '1',
        expectVolatility: '1',
      });
      this.props.handleSelectChange('1', 'expectReturn');
      this.props.handleSelectChange('1', 'expectVolatility');
    }
  };

  //重置表单
  reset = () => {
    this.props.form.resetFields();
  };

  submit = () => {
    if (this.props.type == '0') {
      this.state.RangeDateC.hasRequired();
    }
    let data;
    this.props.form.validateFields((err, values) => {
      if (err) return;
      data = values;
    });
    return data;
  };

  render() {
    return <div className='header-search'>{this.setDataSource()}</div>;
  }
}

// props类型
InitFormC.propsTypes = {
  type: PropTypes.string, //1--股票，2--债券，3--基金，4--多资产
  currentModel: PropTypes.number, //优化模型，
  selectCurrent: PropTypes.func, // 切换列表是否下拉表格变化
  handleSelectChange: PropTypes.func, // 优化模型切换
};
export default connect(({ globalM }) => ({ globalM }))(InitFormC);
